/*global window: false*/
/*
 * #depends subsonic-application.js
 */
Ext.regController('Ext.ux.mattgoldspink.subsonic.controllers.Setup', {
    urls: ['', '/subsonic', '/music'],
    params: {},
    i: -1,
    detect: function() {
        if (!Ext.isDefined(Ext.ux.mattgoldspink.subsonic.apiUrl)) {
            Ext.apply(this.params, Ext.ux.mattgoldspink.subsonic.LoginDetails);
            this.makeRequest();
        } else {//end if
            Ext.dispatch({
                controller: 'Ext.ux.mattgoldspink.subsonic.controllers.User',
                action: 'login'
            });
        }
    },
    doSuccess: function(response){
        var node = Ext.decode(response.responseText);
        if (node) {
            Ext.Msg.hide();
            window.subtunes.userPrefsStore.setApiUrl(this.urls[this.i]);
            Ext.dispatch({
                controller: 'Ext.ux.mattgoldspink.subsonic.controllers.User',
                action: 'login'
            });
            Ext.dispatch({
                controller: 'Ext.ux.mattgoldspink.subsonic.controllers.Player',
                action: 'initialise'
            });
        } else {
            this.makeRequest();
        }
    },
    doFailure: function(response) {
           if (response.status === 404) {
               this.makeRequest();
           } else {
               this.doSuccess(response);
        }
    },
    makeRequest: function() {
        if (this.i === this.urls.length) {
            Ext.Msg.hide();
            Ext.Msg.prompt(
                'Subsonic url', 
                'Enter the url to subsonic:', function(btn, text){
                    if (btn == 'ok'){
                        this.urls.push(text);
                        Ext.Msg.hide();
                    }
                }
            ); // end Ext.Msg.prompt
        } else {
            var loc = window.location;
            Ext.Msg.show({
               msg: 'Attempting to auto discover subsonic api url...<br>Testing: ' + loc.protocol + '//' + loc.host + this.urls[++this.i],
               buttons: false
               });
            Ext.Ajax.request({
                   url: this.urls[this.i] + '/rest/ping.view',
                   params: this.params,
                   scope: this,
                   success: this.doSuccess,
                   failure: this.doFailure
            });// end Ext.Ajax.request
        }// end else
    }// end makeRequest()
});
